/**
  ******************************************************************************
  * @file           : mp3_hw.c
  * @version        : v0.1
  * @brief          : Source file.
  ******************************************************************************
  * @attention
  *
  ******************************************************************************
  */
#include "mp3_hw.h"
#include "heap.h"

DMA_HandleTypeDef hdma_memtomem_dma2_channel1; /* 数据传输DMA，MP3Buf的数据搬运 */

static void DMA_DataTransfer_Init(void);

void mp3_hw_init(void)
{
    /* HAL Initialization */
    MX_TIM4_Init();     /* TIM4 to Generate Sample pulse */
    MX_TIM3_Init();     /* TIM3 to Change Sample Rate */
    MX_DAC_Init();
    DMA_DataTransfer_Init();
}

static void DMA_DataTransfer_Init(void)
{
    __HAL_RCC_DMA2_CLK_ENABLE();

    /* Configure DMA request hdma_memtomem_dma2_channel1 on DMA2_Channel1 */
    hdma_memtomem_dma2_channel1.Instance = DMA_MP3_DATA;
    hdma_memtomem_dma2_channel1.Init.Direction = DMA_MEMORY_TO_MEMORY;
    hdma_memtomem_dma2_channel1.Init.PeriphInc = DMA_PINC_ENABLE;
    hdma_memtomem_dma2_channel1.Init.MemInc = DMA_MINC_ENABLE;
    hdma_memtomem_dma2_channel1.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
    hdma_memtomem_dma2_channel1.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
    hdma_memtomem_dma2_channel1.Init.Mode = DMA_NORMAL;
    hdma_memtomem_dma2_channel1.Init.Priority = DMA_PRIORITY_LOW;
    if (HAL_DMA_Init(&hdma_memtomem_dma2_channel1) != HAL_OK)
    {
        Error_Handler();
    }
}

void mp3_hw_data_DMA(short *src, short *dest, uint32_t length)
{
    /* clear flag */
    LL_DMA_ClearFlag_GI1(DMA_MP3_DATA_CONTROLER);

    LL_DMA_DisableChannel(DMA_MP3_DATA_CONTROLER, DMA_MP3_DATA_CHANNEL);
    LL_DMA_SetM2MSrcAddress(DMA_MP3_DATA_CONTROLER, DMA_MP3_DATA_CHANNEL, (uint32_t)src);
    LL_DMA_SetM2MDestAddress(DMA_MP3_DATA_CONTROLER, DMA_MP3_DATA_CHANNEL, (uint32_t)dest);
    LL_DMA_SetDataLength(DMA_MP3_DATA_CONTROLER, DMA_MP3_DATA_CHANNEL, length);
    LL_DMA_EnableChannel(DMA_MP3_DATA_CONTROLER, DMA_MP3_DATA_CHANNEL);

    LL_DMA_EnableIT_TC(DMA_MP3_DATA_CONTROLER, DMA_MP3_DATA_CHANNEL);
}